from DrissionPage import ChromiumPage
from utils.parse import parseURL
from datetime import datetime
import json


# 过去一个月的日期
DateLine = datetime.strptime('2025-03-29', '%Y-%m-%d')
print("截止日期", DateLine)
print("类型", type(DateLine))

toatl_urls = {
    "九牧": {},
    "箭牌": {},
    "瑞尔特": {},
    "恒洁": {},
}

def save_dict_to_json(filename, dictionary):
    with open(filename, 'w', encoding='utf-8') as file:
        json.dump(dictionary, file, ensure_ascii=False, indent=4)

def get_video_date(dateStr):
    if '-' not in dateStr:
        return datetime.now()
    elif '2024' in dateStr:
        return DateLine
    # 传入的是时间字符串: months-day
    # 字符串拼接上年份, 转换为datetime对象
    dateStr = dateStr[dateStr.find(' ')+1:]
    dateStr = '2025-' + dateStr
    videoDate = datetime.strptime(dateStr, '%Y-%m-%d')

    return videoDate

def get_last_month_period_url(page, lable):
    # 获取页面内容
    page.wait.title_change('下一页')  # 等待title变化出现目标文本
    page.stop_loading()  # 主动停止加载

    # 获取页面 HTML 内容
    elements = page.eles('.bili-video-card')

    # 遍历每个元素并获取其中的 a 标签的链接
    for element in elements:
        links = element.eles('.bili-video-card__wrap')
        for link in links:
            date = link.eles('.bili-video-card__info--date')
            if get_video_date(date[0].text) < DateLine:
                return
            
            titles = link.ele('.bili-video-card__info--tit').attr('title')
            if "马桶" in titles:
                productType = "马桶"
            elif "浴室柜" in titles:
                productType = "浴室柜"
            elif "淋浴器" in titles:
                productType = "淋浴器"
            else:
                productType = None

            if productType is None:
                continue

            # 保存链接信息 和 a 标签
            herf = link.eles('tag:a')[0].link
            toatl_urls[lable].setdefault(productType, []).append(herf)

    button = page.eles('.vui_button vui_pagenation--btn vui_pagenation--btn-side')
    if len(button) > 0:
        button[-1].click()
        get_last_month_period_url(page, lable)

if  __name__ == '__main__':

    page = ChromiumPage()
    page.set.load_mode.none()  # 设置加载模式为none

    spiderList = ["九牧", "箭牌", "瑞尔特", "恒洁"]
    # 目标 URL，搜索“九牧 智能马桶”
    for spider in spiderList:
        url = f"https://search.bilibili.com/all?keyword={spider}&from_source=webtop_search&spm_id_from=333.1007&search_source=5&order=pubdate"

        page.get(url)  # 访问网站
        get_last_month_period_url(page, lable=spider)

    print(toatl_urls)
    save_dict_to_json('bilibili-url.json', toatl_urls)

    # url = 'https://www.bilibili.com/video/BV1SkZ6YUE4w/'
    # tab = page.get_tab()
    # parse = parseURL(url, tab)
    # parse.parseData()

    # for url in herfs:
    #     parse = parseURL(url, tab)
    #     parse.parseData()